# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>

import subprocess
import os
import logging

logger = logging.getLogger("excavator.util")

"""
Shell command util functions
"""


def run_cmd(cmd, env=None):
    if env is None:
        env = {}
    try:
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf8', shell=True,
                                   env=env)
        output, _ = process.communicate()
        return process.returncode, output
    except Exception as e:
        logger.error(e)
        return -1, e


def c_run_cmd(cmd):
    return run_cmd(cmd, {"LANG": "C"})


def run_cmd_realtime_out(cmd):
    try:
        env = os.environ.copy()
        env["LANG"] = "C"
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, encoding='utf8', shell=True, env=env)
        while True:
            output = process.stdout.readline()
            if output == '' and process.poll() is not None:
                break
            if output:
                print(output.strip())
        rc = process.poll()
        return rc
    except Exception as e:
        logger.error(e)
        return -1
